package com.n9.buymsg.service.qqonline.converter;

import com.n9.buymsg.service.qqonline.MsgType;
import com.n9.buymsg.service.qqonline.converter.MsgConverter;
import com.n9.buymsg.service.qqonline.converter.PurchaseMessageFilter;
import com.n9.qq.android.AqContext;
import com.n9.qq.android.im.msg.Elem;
import com.n9.qq.android.im.msg.RichText;
import com.n9.qq.android.msg_comm.Msg;
import com.n9.qq.android.msg_comm.MsgHead;
import com.n9.sdk.model.PurchaseMessage;
import com.vdurmont.emoji.EmojiParser;

import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 求购消息转换器
 * @Author: ice
 * @Date: 2020-07-06 8:59
 */
public class PurchaseMessageConverter implements MsgConverter<PurchaseMessage> {
    private List<PurchaseMessageFilter> filters = new ArrayList<>();

    @Override
    public Optional<PurchaseMessage> convert(Msg msg, AqContext context) {
        MsgHead msgHead = msg.msg_head;
        long sender = msgHead.from_uin.get();
        String sendNick = msgHead.from_nick.get();
        long receiver = msgHead.to_uin.get();
        long groupCode = msgHead.group_info.group_code.get();
        long msgUid = msgHead.msg_uid.get();
        int msgType = msgHead.msg_type.get();
        long msgSeq = msgHead.msg_seq.get();

        String groupName = context.getTroopNameByCode(groupCode);
        String content = richTextToStringMsg(msg.msg_body.rich_text);

        PurchaseMessage purchaseMessage = null;
        if (content.length() > 0) {
            //过滤表情字符
            content = EmojiParser.removeAllEmojis(content);
            sendNick = EmojiParser.removeAllEmojis(sendNick);
            groupName = EmojiParser.removeAllEmojis(groupName);

            purchaseMessage = new PurchaseMessage();
            purchaseMessage.setMsgId(msgUid);
            purchaseMessage.setMsgSeq(msgSeq);
            purchaseMessage.setMsgType(Optional.ofNullable(MsgType.convert(msgType)).map(type -> type.toString()).orElse("UNKNOWN"));
            purchaseMessage.setSender(Long.toString(sender));
            purchaseMessage.setSenderNickname(sendNick);
            purchaseMessage.setReceiver(Long.toString(receiver));
            purchaseMessage.setReceiverNickname("");
            purchaseMessage.setFromGroup(Long.toString(groupCode));
            purchaseMessage.setFromGroupNickname(groupName);
            long msgTime = msgHead.msg_time.get() * 1000L;
            purchaseMessage.setReceiveTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(msgTime), ZoneId.systemDefault()));
            purchaseMessage.setContent(content);

        }
        return Optional.ofNullable(purchaseMessage);
    }

    /**
     * 富文本消息转纯文本消息，过滤表情、图片等
     * @param richText
     * @return
     */
    private String richTextToStringMsg(RichText richText) {
        StringBuilder textMsg = new StringBuilder();
        richText.elems.get().forEach(o ->{
            Elem ele = (Elem) o;
            byte[] bytes = ele.text.str.get().toByteArray();
            if (bytes.length > 0) {
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] == 0x0D) {
                        bytes[i] = 0x0A;
                    }
                }
                try {
                    textMsg.append(new String(bytes, "UTF-8").trim());
                } catch (UnsupportedEncodingException e) {
                    //ignore
                }
            }
        });
        return textMsg.toString();
    }
}
